package com.jing.system.tags.loadresource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * 加载Js资源的Tag
 * @author jing.yue
 * @version 1.0
 * @since 2012-10-12
 */
public class JsTag extends TagSupport {

	private static final long serialVersionUID = -4720851118041402523L;

	/**
	 * 保存jslib的Map集合<br>
	 * key:		路径的别名<br>
	 * value:	路径名称<br>
	 */
	public static Map<String, String> jsMap = new HashMap<String, String>();

	private String jslibs;

	private String webroot;

	@Override
	public int doStartTag() throws JspException {
		try {
			JspWriter out = this.pageContext.getOut();
			List<String> jslibList = LoadResource.getLibsArr(this.jslibs);
			if(jslibList == null || jslibList.size() == 0) {
				return SKIP_BODY;
			}
			StringBuffer jslibStr= new StringBuffer();
			for (String jslib : jslibList) {
				jslibStr.append("<script type=\"text/javascript\" src=\"" + webroot + jsMap.get(jslib) + "\"></script>");
			}
			jslibStr.append("<script type=\"text/javascript\">var webroot = \"" + webroot + "\";</script>");
			out.print(jslibStr);
		} catch(Exception e) {
			throw new JspException(e.getMessage());
		}
		return SKIP_BODY;
	}

	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}

	/**
	 * 生命周期结束时调用
	 */
	@Override
	public void release() {
		super.release();
		jslibs = null;
	}

	public String getJslibs() {
		return jslibs;
	}

	public void setJslibs(String jslibs) {
		this.jslibs = jslibs;
	}

	public String getWebroot() {
		return webroot;
	}

	public void setWebroot(String webroot) {
		this.webroot = webroot;
	}
}